<template>
<div class="headerSearch">
  <input
    class="inputSearch"
    v-model='keyword'
    type="text"
    placeholder="输入城市名或拼音"
  >
  <div class="searResult" ref="search" v-show='keyword'>
    <ul>
      <li
        class="searResultItem border-bottom"
        v-for='item of list'
        :key='item.id'
        @click = 'handleCityClick(item.name)'
        >{{item.name}}</li>
      <li class="searResultItem border-bottom" v-show='hasNoData'>没有找到匹配数据</li>
    </ul>
  </div>
</div>
</template>
<script>
import BScroll from 'better-scroll'
export default{
  name: 'citySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.dispatch('changeCity', city)
      this.$router.push('/')
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        let result = []
        for (let i in this.cities) {
          // console.log('1:' + this.cities[i])
          this.cities[i].forEach((value) => {
            // console.log('2:' + value)
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 200)
      // console.log(this.list)
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.search, {
      click: true
    })
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.headerSearch
  height: .62rem
  background-color: $bgcolor
  padding: 0 .1rem
  .inputSearch
    box-sizing: border-box
    padding: 0 .1rem
    width: 100%
    height: .5rem
    border-radius: .1rem
    color: #666
    text-align: center
  .searResult
    overflow: hidden
    position: absolute
    z-index: 1
    top: 1.48rem
    left: 0
    right: 0
    bottom: 0
    background-color: #eee
    .searResultItem
      line-height: .62rem
      background-color: #fff
      padding-left: .2rem
</style>
